<?php 
include("util.php");
include("header.php");
?>
<?php
$conn = mysql_connect("127.0.0.1","root","");
mysql_select_db("xingtan");

$text = $_GET['q'];
$start = intval($_GET['s']);
if ($start == null) {
  $start = 1;
}
$sort_by_time = intval($_GET['t']);
$count_per_page = 10;
$current_page = $start;
$start = ($start - 1) * 10;
?>

<!--
<title><?php echo $text ?>_搜索_价值投资派 ，汇聚价值投资智慧</title>
-->

<style type="text/css">
a.search_title {
  text-decoration:underline;
  line-height:22px;
  font-size:15px;
}
.search_digest {
  color:#333;font-size:13px;text-decoration:none;
  line-height:22px;
}
a.search_url {
  color:#191;font-size:12px;
}
div.search-result-item {
  /*margin:4px 0 16px;*/
  width: 80%;
  margin-bottom:4px; padding:12px; background-color:white;-moz-border-radius: 10px;-webkit-border-radius: 10px;border-radius: 10px;
}
div.search-box-big input {
font-size:16px;
line-height:20px;
}
</style>
<div class="container">
<div style="height:6px;"></div>
<div class="search-box-big">
<input tabindex="1" maxlength="100" size="42" value="<?php echo $text; ?>" class="search-word"> 
&nbsp; <input class="search-btn" type="button" value="搜索"/> &nbsp; <input type="checkbox" name="sort_by_time">搜索结果按时间排序
</div>
<?php
if ($sort_by_time) {
  $search_res = SearchByTime($text, $start, $count_per_page);
} else {
  $search_res = Search($text, $start, $count_per_page);
}
$total_pages = ceil($search_res->total_count / $count_per_page);

printf('<span style="font-size:12px;magrin-bottom:3px;color:#888;">搜索到<span style="font-weight:bold;color:red">%d</span>篇文章</span><br/>', $search_res->total_count);

CommonPageNav($total_pages, 10, $current_page, 4, sprintf("/search?q=%s&s=%%d&t=%d", str_replace('%', '%%', urlencode($text)), $sort_by_time));

class ColorOffset {
  public $start = null;
  public $end = null;
  function __construct($s, $e) {
    $this->start = $s;
    $this->end = $e;
  }
}

function InsertOffset($offsets, $item) {
  $len = count($offsets);

  for($i = $len - 1; $i >= 0; --$i) {
    if ($item->start > $offsets[$i]->start) {
      $res = array_merge(array_slice($offsets, 0, $i + 1), array($item), array_slice($offsets, $i + 1));
      return $res;
    }
  }
  return array_merge(array($item), array_slice($offsets, 0));
}

function MergeColorOffset($offsets) {
  do {
    $do_merge = false;
    $index = 0;

    foreach($offsets as $co) {
      // print 'index = ' . $index . '<br/>';
      if ($index > 0) {
        if ($co->start <= $prev->end) {
          // printf("%d %d unset an item ---------- <br/>", $co->start, $prev->end);
          if ($prev->end < $co->end) {
            $prev->end = $co->end;
            // print "use current end : " . $co->end . "<br/>";
          }
          // print count($offsets) . '=';
          unset($offsets[$index]);
          // ++$index;
          // print count($offsets) . '=';
          $do_merge = true;
        }
      } else {
        $prev = $offsets[$index];
      }
      ++$index;
    }
  }while($do_merge);

  return $offsets;
}

function ColorText($words, $text) {
  // $words = array('银行');
  $offsets = array();
  foreach($words as $word) {
    $pos = strpos($text, $word);
    while(!($pos === false)) {
      // print $word . $pos. '<br/>';
      $offsets = InsertOffset($offsets, new ColorOffset($pos, $pos + strlen($word)));
      $pos = strpos($text, $word, $pos + strlen($word));
    }
  }
  
  foreach($offsets as $o) {
    // printf('offsets : %d %d<br/>', $o->start, $o->end);
  }

  $offsets = MergeColorOffset($offsets);
  foreach($offsets as $o) {
    // printf('merged offsets : %d %d<br/>', $o->start, $o->end);
  }

  $res = '';
  $pos = 0;
  foreach($offsets as $o) {
    $res = $res . substr($text, $pos, $o->start - $pos);
    $res = $res . '<span style="color:red;">';
    $res = $res . substr($text, $o->start, $o->end - $o->start);
    $res = $res . '</span>';

    $pos = $o->end;
  }
  $res = $res . substr($text, $pos);
  return $res;
}

function GetMatchedDigest($content, $words) {
  $offsets = array();
  $prefix = 28;
  $postfix = 100;
  foreach($words as $word) {
    $pos = mb_strpos($content, $word, 0, 'utf-8');
    if(!($pos === false)) {
      $offsets = InsertOffset($offsets, new ColorOffset($pos > $prefix ? $pos - $prefix : 0, $pos + mb_strlen($word, 'utf-8') + $postfix));
    }
  }
  foreach($offsets as $o) {
    // printf('digest offsets : %d %d<br/>', $o->start, $o->end);
  }
  // return '........';
  $offsets = MergeColorOffset($offsets);

  foreach($offsets as $o) {
    // printf('merged digest offsets : %d %d<br/>', $o->start, $o->end);
  }
  $digest = '';

  foreach($offsets as $o) {
    if ($o->start > 0 && strlen($digest) == 0) {
      $digest = '...';
    }

    //   return mb_substr($str, 0, $max_len - 1, 'utf-8') . '...';
    $digest = $digest . mb_substr($content, $o->start, $o->end - $o->start, 'utf-8');
    $digest = $digest . '...';
  }

  return $digest;
}

include_once(dirname(__FILE__) . "/article-main-adapter.php");
$article_main_adapter = new ArticleMainAdapter();

foreach ($search_res->article_ids as $i => $article_id) {
  $meta = GetArticleMeta($article_id);
  printf('<div class="search-result-item">');
  printf('<a class="search_title" href="/a/%d.html?f=stitle" target="_blank">%s</a><br/>', $article_id, ColorText($search_res->seg_words, $meta['a_title']));

  $content = $article_main_adapter->GetContent($article_id);
  $digest = GetMatchedDigest(str_replace('&nbsp;', '', strip_tags($content)), $search_res->seg_words);
  // $digest = str_replace($digest, ' ', '');
  printf('<span class="search_digest">%s</span><br/>', ColorText($search_res->seg_words, $digest));
  printf('<a class="search_url" href="/a/%d.html?f=surl" target="_blank">http://www.jztzp.com/a/%d.html</a> &nbsp; <span style="color:#666;font-size:12px;">%s</span><br/>', $article_id, $article_id, $meta['a_create_time']);
  printf('</div>');
}
printf('<div style="height:6px;"></div>');
CommonPageNav($total_pages, 10, $current_page, 4, sprintf("/search?q=%s&s=%%d&t=%d", str_replace('%', '%%', urlencode($text)), $sort_by_time));
?>

<div class="search-box-big">
<input tabindex="1" maxlength="100" size="42" value="<?php echo $text; ?>" class="search-word"> 
&nbsp; <input class="search-btn" type="button" value="搜索"/> &nbsp; <input type="checkbox" name="sort_by_time">搜索结果按时间排序
</div>
</div>

<?php 
include("footer.php");
?>

